package com.ljm.security.loginprocessor;

import com.alibaba.fastjson.JSON;
import com.ljm.security.enums.LoginTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletRequest;
import java.io.IOException;

import static org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY;
import static org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY;

/**
 * @author: ChenHuaMing
 * @Date: 2020/6/12 16:30
 * @Description: JSON类型登录
 */
@Slf4j
public class JsonLoginPostProcessor implements LoginPostProcessor {
    @Override
    public LoginTypeEnum getLoginTypeEnum() {
        return LoginTypeEnum.JSON;
    }

    @Override
    public String obtainUsername(ServletRequest request) {
        try {
            String loginJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            return JSON.parseObject(loginJson).getString(SPRING_SECURITY_FORM_USERNAME_KEY);
        } catch (IOException e) {
            log.error("JsonLoginPostProcessor get username error",e);
            return null;
        }
    }

    @Override
    public String obtainPassword(ServletRequest request) {
        try {
            String loginJson = IOUtils.toString(request.getInputStream(), "UTF-8");
            return JSON.parseObject(loginJson).getString(SPRING_SECURITY_FORM_PASSWORD_KEY);
        } catch (IOException e) {
            log.error("JsonLoginPostProcessor get password error",e);
            return null;
        }
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}
